package com.google.gwt.it2tool.client.widget;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.it2tool.client.ClientDataCache;
import com.google.gwt.it2tool.client.ClientDataCache.DataChangeHandler;
import com.google.gwt.it2tool.client.Production;
import com.google.gwt.it2tool.client.widget.ProductLabel.IProductClickedHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;

public abstract class ProductFlexTable extends FlexTable {
	
	protected ClientDataCache dataCache;
	
	public ProductFlexTable(){
		super();
		dataCache = ClientDataCache.getInstance();		
	}
	
	protected void setDataChangeHandler(final DataChangeHandler handler){
		addAttachHandler(new Handler() {
			
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if (event.isAttached()){
					dataCache.addDataChangeHandler(handler);
				}else{
					dataCache.removeDataChangeHandler(handler);
				}
				
			}
		});
	}
	
	private ArrayList<IProductClickedHandler> prodClickHandlers = new ArrayList<IProductClickedHandler>();

	protected Label getProductLabel(Production production){
		ProductLabel label = new ProductLabel(production);
		label.addIProductClickedHandler(new IProductClickedHandler() {			
			public void onProductClicked(Production production, ClickEvent event) {
				triggerOnProductClicked(production, event);				
			}
		});
		return label;
	}
	
	public void addProductClickedHandler(IProductClickedHandler handler){
		prodClickHandlers.add(handler);
	}
	
	public void removeProductClickedHandler(IProductClickedHandler handler){
		if(handler!=null && prodClickHandlers.contains(handler)){
			prodClickHandlers.remove(handler);
		}
	}
	
	public void triggerOnProductClicked(Production production,ClickEvent event){
		for(IProductClickedHandler h: prodClickHandlers){
			h.onProductClicked(production, event);
		}
	}
}
